import {
	ITreeViewController,
	TreeViewActionType,
	IParam,
	ITreeViewAbility,
	ITreeViewStore,
	ITreeAbility,
	SearchFormActionType,
	IViewActionResult,
	ICtrlActionResult,
} from '@/core/interface';
import { MDViewController } from './md-view-controller';

/**
 * 树视图视图控制器
 *
 * @export
 * @class TreeViewController
 * @extends {ViewController}
 */
export class TreeViewController
	extends MDViewController<TreeViewActionType, ITreeViewStore, ITreeViewAbility>
	implements ITreeViewController<ITreeViewStore, ITreeViewAbility>
{
	/**
	 * 获取树部件能力
	 *
	 * @protected
	 * @return {*}  {(ITreeAbility | undefined)}
	 * @memberof TreeViewController
	 */
	protected getMainCtrlAbility(): ITreeAbility | undefined {
		const tree = this.model.ctrls.find(
			(ctrl: IParam) => ctrl.controlType === 'TREEVIEW'
		);
		if (tree) {
			return this.getSubAbility<ITreeAbility>(tree.name);
		}
		return undefined;
	}

	/**
	 * 快速分组值变化
	 *
	 * @param {IParam} item
	 * @memberof TreeViewController
	 */
	public handleQuickGroupValueChange(item: IParam) {
		if (item) {
			this.queryParams.quickGroupData = item.data;
			const mdCtrl = this.getMainCtrlAbility();
			if (mdCtrl) {
				mdCtrl.refreshAllNode();
			}
		}
		this.isEmitQuickGroupValue = true;
	}

	/**
	 * 处理搜索表单部件行为
	 *
	 * @protected
	 * @param {SearchFormActionType} action
	 * @param {IParam[]} data
	 * @memberof TreeViewController
	 */
	protected handleSearchFormAction(
		action: SearchFormActionType,
		data: IParam[]
	) {
		const mdCtrl = this.getMainCtrlAbility();
		if (mdCtrl) {
			if (action === 'load') {
				mdCtrl.load();
			}
			if (action === 'search') {
				mdCtrl.refreshAllNode();
			}
		}
	}

	/**
	 * 视图加载
	 *
	 * @param {IParam} [args]
	 * @return {*}  {Promise<IViewActionResult>}
	 * @memberof TreeViewController
	 */
	public load(args?: IParam): Promise<IViewActionResult> {
		const mdCtrl = this.getMainCtrlAbility();
		if (mdCtrl) {
			return mdCtrl.load();
		} else {
			return Promise.reject({
				ok: false,
				data: null,
				rowData: { status: 500 },
			});
		}
	}

	/**
	 * 搜索
	 *
	 * @param {string} searchValue
	 * @memberof TreeViewController
	 */
	public search(searchValue: string) {
		this.queryParams.query = searchValue;
		const mdCtrl = this.getMainCtrlAbility();
		if (mdCtrl) {
			mdCtrl.refreshAllNode({ query: searchValue });
		}
	}

	/**
	 * 刷新
	 *
	 * @param {(IParam | undefined)} [args]
	 * @return {*}  {Promise<IViewActionResult>}
	 * @memberof TreeViewController
	 */
	public async refresh(args?: IParam | undefined): Promise<boolean> {
		const mdCtrl = this.getMainCtrlAbility();
		if (mdCtrl) {
			return (await mdCtrl.refreshAllNode({ query: this.queryParams.query }))
				.ok;
		}
		return Promise.reject(false);
	}
}
